<template>
  <div class="container">
    <el-card shadow="never" style="margin-bottom: 16px; display:flex; align-items:center; gap:12px;">
      <el-input v-model="keyword" placeholder="搜索标题..." @keyup.enter="onSearch" clearable style="max-width: 320px;" />
      <el-select v-model="category" placeholder="选择分类" clearable style="width: 180px;">
        <el-option v-for="c in categories" :key="c.name" :label="c.name + ' (' + c.count + ')'" :value="c.name" />
      </el-select>
      <el-button type="primary" @click="onSearch">搜索</el-button>
      <el-button @click="onReset" v-if="keyword || category">重置</el-button>
    </el-card>

    <el-skeleton v-if="loading" :rows="5" animated />
    <template v-else>
      <el-empty v-if="list.length === 0" description="暂无文章" />
      <el-card v-for="p in list" :key="p.id" shadow="hover" style="margin-bottom: 16px;" @click="$router.push(`/article/${p.id}`)">
        <h3 style="margin: 0 0 8px;">{{ p.title }}</h3>
        <div class="muted">{{ p.date }} · {{ p.tags.join(', ') }}</div>
        <p>{{ p.summary }}</p>
      </el-card>
      <div style="display:flex;justify-content:center;margin:16px 0;">
        <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total" :current-page="page" @current-change="onPageChange" />
      </div>
    </template>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchPosts, fetchCategories } from '@/services/blogService'

const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(5)
const loading = ref(false)
const route = useRoute()
const router = useRouter()
const keyword = ref(route.query.q || '')
const category = ref(route.query.category || '')
const categories = ref([])

async function load() {
  loading.value = true
  const { list: l, total: t } = await fetchPosts({ page: page.value, pageSize: pageSize.value, keyword: keyword.value, category: category.value })
  list.value = l
  total.value = t
  loading.value = false
}

function onPageChange(p) { page.value = p; syncToUrl(); load() }

function syncToUrl() {
  const q = {}
  if (keyword.value) q.q = keyword.value
  if (category.value) q.category = category.value
  if (page.value && page.value !== 1) q.page = String(page.value)
  router.replace({ query: q })
}

function initFromUrl() {
  const q = route.query
  keyword.value = q.q || ''
  category.value = q.category || ''
  page.value = q.page ? Number(q.page) : 1
}

function onSearch() { page.value = 1; syncToUrl(); load() }
function onReset() { keyword.value = ''; category.value = ''; page.value = 1; syncToUrl(); load() }

onMounted(async () => {
  initFromUrl()
  categories.value = await fetchCategories()
  await load()
})

watch(() => route.query, () => { initFromUrl(); load() })
</script>

<style scoped>
.muted { color: var(--color-muted); }
</style>


